package handler

import (
	"design-hub/cache"
	"design-hub/models"
	"encoding/json"
	"strconv"
	"time"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

func Del(c *gin.Context) {
	id := c.Query("id")
	err := models.DB.Where("id=?", id).Delete(&models.Hub{}).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	}
	redis_key := "add_" + id
	cache.Rdb.Del(cache.Ctx, redis_key)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "删除成功",
	})
}
func Add(c *gin.Context) {
	title := c.PostForm("title")
	info := c.PostForm("info")
	if title == "" || info == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "不可为空",
		})
		return
	}
	data := models.Hub{
		Model: gorm.Model{},
		Title: title,
		Info:  info,
	}
	err := models.DB.Create(&data).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "add_" + strconv.Itoa(int(data.ID))
	var hub models.Hub
	models.DB.Where("id=?", data.ID).First(&hub)
	jsonData, _ := json.Marshal(hub)
	cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func List(c *gin.Context) {
	var hub []models.Hub
	redis_key := "list"
	ca, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if ca == "" {
		models.DB.Find(&hub)
		jsonC, _ := json.Marshal(hub)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonC, time.Hour*2)
	} else {
		json.Unmarshal([]byte(ca), &hub)
	}
	var total int64
	models.DB.Model(&models.Hub{}).Count(&total)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"data": hub,
	})
}
